//
//  QRAlert.m
//  testAlert
//
//  Created by Hshd on 15/6/29.
//  Copyright © 2015年 Hshd. All rights reserved.
//

#import "SDAlert.h"
#import "UIImage+ImageEffects.h"

typedef void(^myBlock)();

#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self


@interface SDAlert()
{
    BOOL isCancel;
}

@property (nonatomic , strong) UIImageView *backgroundView;
@property (nonatomic , strong) UIView *alertView;


@end

@implementation SDAlert


/**
 *  自定义alertView
 *
 *  @param alertView 传入的alertView
 *  @param frame     alertView的frame
 *  @param isCancel  点击空白是否可以取消显示
 */
- (instancetype)initWithAlertView:(UIView *)alertView frame:(CGRect)frame isCancel:(BOOL)cancel
{
    self = [super init];
    if (self)
    {
        self.tag = 1028;
        
        isCancel = cancel;
        
        myBlock block1 = ^{
        
            [self makeAlertPopupViewWithView:alertView frame:frame];
        
        };

        [self initWithBlock:block1];
    }
    
    return self;
}

- (void)initWithBlock:(myBlock)block
{
    //添加蒙版
    [self makeBackgroundBlur];
    
    //添加View
    block();
    //添加特效
    [self moveAlertPopupView];
    
    //添加动画
    [self showAnimation];
    
}


- (instancetype)initWithTitle:(NSString *)title descTitle:(NSString *)descTitle
{
    self = [super init];
    
    self.tag = 1028;
    
    WS(weakSelf);
    
    if (self)
    {
        [weakSelf cancelUserEnable];
        isCancel = NO;
        
        myBlock block1 = ^{
            
            UIView *tipsView = [[UIView alloc] init];
            tipsView.backgroundColor = [UIColor whiteColor];
            tipsView.frame = CGRectMake(0, 0, 200, 120);
            
            UILabel *label = [[UILabel alloc] init];
            label.center = CGPointMake(100, 20);
            label.frame = CGRectMake(70, 10,200,20);
            
            label.textColor = [UIColor blackColor];
            label.font = [UIFont boldSystemFontOfSize:15.0];
            label.text = title;
            [tipsView addSubview:label];
            
            UILabel *desclabel = [[UILabel alloc] init];
            desclabel.frame = CGRectMake(20, 40, 200, 20);
            desclabel.textColor = [UIColor cyanColor];
            desclabel.font = [UIFont boldSystemFontOfSize:13.0];
            desclabel.text = descTitle;
            [tipsView addSubview:desclabel];
            
            UIButton *sureBtn = [[UIButton alloc] init];
            sureBtn.frame = CGRectMake(20, 80, 60, 40);
            [sureBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
            [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            sureBtn.backgroundColor = [UIColor redColor];
            sureBtn.layer.cornerRadius = 8.0;
            sureBtn.tag = 23450;
            [tipsView addSubview:sureBtn];
            
            UIButton *cancelBtn = [[UIButton alloc] init];
            cancelBtn.frame = CGRectMake(120, 80, 60, 40);
            [cancelBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
            [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            cancelBtn.backgroundColor = [UIColor redColor];
            cancelBtn.layer.cornerRadius = 8.0;
            cancelBtn.tag = 23451;
            [tipsView addSubview:cancelBtn];
            
            [self resignFirstResponder];
     
            [weakSelf makeAlertPopupViewWithView:tipsView frame:CGRectMake(0, 0, 200, 120)];
            
        };
        
        [self initWithBlock:block1];
    }
    
    return self;
}

/**
 *  取消用户交互
 */
- (void)cancelUserEnable
{
    
    [[UIApplication sharedApplication].keyWindow.subviews enumerateObjectsUsingBlock:^(UIView * obj, NSUInteger idx, BOOL *stop) {
        
        obj.userInteractionEnabled = NO;
        
        NSLog(@"rkeywindowroot --- %ld",[UIApplication sharedApplication].keyWindow.superview.tag);
        
    }];
    
}

/**
 *  显示
 */
-(void)show
{
    if (isCancel)
    {
        self.backgroundView.userInteractionEnabled = YES;
        
        [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [tap addTarget:self action:@selector(tapGestureClick:)];
        [[UIApplication sharedApplication].keyWindow addGestureRecognizer:tap];
        
    }
    
    UIWindow *wind = [UIApplication sharedApplication].keyWindow;
    wind.userInteractionEnabled = YES;
    
    NSLog(@"keyWindow --- %@",[UIApplication sharedApplication].keyWindow.subviews);
    
    self.frame = [self mainScreenFrame];
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    NSLog(@"keywin.userenable --- %d",[UIApplication sharedApplication].keyWindow.userInteractionEnabled);
    
    NSLog(@"sksksk --- %@",[UIApplication sharedApplication].keyWindow.subviews);

}

/**
 *  产生蒙版
 */
- (void)makeBackgroundBlur
{
    self.backgroundView = [[UIImageView alloc]initWithFrame:[self mainScreenFrame]];
    UIImage *image = [UIImage convertViewToImage];
    UIImage *blurSnapshotImage = nil;
    blurSnapshotImage = [image applyBlurWithRadius:5.0
                                         tintColor:[UIColor colorWithWhite:0.2
                                                                     alpha:0.7]
                             saturationDeltaFactor:1.8
                                         maskImage:nil];
    
    self.backgroundView.image = blurSnapshotImage;
    self.backgroundView.alpha = 0;
    
    [self addSubview:self.backgroundView];
}

#pragma mark - Util Methods
- (CGRect)mainScreenFrame
{
    return [UIScreen mainScreen].bounds;
}

/**
 *  中间提示的部分
 *
 *  @param alertView 提示的View
 *  @param frame     中间alertView的frame
 */
- (void)makeAlertPopupViewWithView:(UIView *)alertView frame:(CGRect)frame
{
    
    CGRect screen = [self mainScreenFrame];
    
    self.alertView = [[UIView alloc]initWithFrame:frame];
    
    self.alertView.userInteractionEnabled = YES;
    
    self.alertView.center = CGPointMake(CGRectGetWidth(screen)/2, CGRectGetHeight(screen)/2);
    
    self.alertView.layer.masksToBounds = YES;
    self.alertView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:1.0f];
    
    [self.alertView addSubview:alertView];
    
    [self addSubview:self.alertView];
}





#pragma mark - View Animation Methods
- (void)moveAlertPopupView
{
    CGRect screen = [self mainScreenFrame];
    
    CATransform3D move = CATransform3DIdentity;
    
    CGFloat initalertViewYPosition = (CGRectGetHeight(screen) + CGRectGetHeight(self.alertView.frame)) / 2;
    
    move = CATransform3DMakeTranslation(0, -initalertViewYPosition, 0);

    self.alertView.layer.transform = move;
}

/**
 *  手势触发
 */
- (void)tapGestureClick:(UITapGestureRecognizer *)gesture
{
    [[UIApplication sharedApplication].keyWindow removeGestureRecognizer:gesture];
    
    [self dismiss];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    
}

/**
 *  显示动画
 */
- (void)showAnimation
{
    
    [UIView animateWithDuration:0.3f animations:^{
        self.backgroundView.alpha = 1.0f;
    }];
    
    
    [UIView animateWithDuration:1.0f
                          delay:0.0f
         usingSpringWithDamping:0.4f
          initialSpringVelocity:0.0f
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         CATransform3D init = CATransform3DIdentity;
                         self.alertView.layer.transform = init;
                         
                     }
                     completion:^(BOOL finished) {
                        
                     }];
    
    
}


- (void)dismiss
{
    
    [UIView animateWithDuration:0.8f
                      delay:0.0f
     usingSpringWithDamping:1.0f
      initialSpringVelocity:0.0f
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     
                     CGRect screen = [self mainScreenFrame];
                     CATransform3D move = CATransform3DIdentity;
                     CGFloat initalertViewYPosition = CGRectGetHeight(screen);
                     
                     move = CATransform3DMakeTranslation(0, initalertViewYPosition, 0);
                     move = CATransform3DRotate(move, -40 * M_PI/180, 0, 0, 1.0f);
                     self.alertView.layer.transform = move;
                     
                     self.backgroundView.alpha = 0.0;
                 }
                 completion:^(BOOL finished){
                     [self.alertView removeFromSuperview];
                     [self.backgroundView removeFromSuperview];
                     
                     [self removeFromSuperview];
                    
                 }];

    [[UIApplication sharedApplication].keyWindow.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        
        obj.userInteractionEnabled = YES;
        
    }];
    
    if ([self.myDelegate respondsToSelector:@selector(alertDelegateDismiss)])
    {
        [self.myDelegate alertDelegateDismiss];
    }
}



/**
 *  按钮点击
 *
 *  @param btn btn
 */
- (void)btnClick:(UIButton *)btn
{
    NSLog(@"点击了alert按钮");
    
    [self dismiss];
    
    if ([self.myDelegate respondsToSelector:@selector(alertDelegateButtonClick:andButtonIndex:)])
    {
        [self.myDelegate alertDelegateButtonClick:btn andButtonIndex:(unsigned int)btn.tag];
    }
}



@end
